package com.itheima.web.manager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminManager {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Reference
    private AdminService adminService;

    //生成验证码
    public LineCaptcha genCaptcha(String uuid) {
        //1. 生成验证图片对象
        LineCaptcha lineCaptcha = new LineCaptcha(300, 100);//设置宽和高

        //2. 将验证码数字保存到redis
        String code = lineCaptcha.getCode();
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE + uuid, code, Duration.ofMinutes(5));

        //3. 将验证码图片对象返回
        return lineCaptcha;
    }

    //管理员登录
    public String login(String username, String password, String verificationCode, String uuid) {
        //1. 先根据uuid从redis中查询验证码并比对,如果比对不中,直接返回错误消息
        String code = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);
        if (!StringUtils.equals(verificationCode, code)) {
            throw new BusinessException("验证码错误");
        }

        //2. 根据username从数据库中查询管理员,如果不存在,直接返回错误消息
        Admin admin = adminService.findByUsername(username);
        if (admin == null) {
            throw new BusinessException("当前管理员不存在");
        }

        //3. 密码比对,如果比对不中,直接返回错误消息
        String passwordWithMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordWithMd5, admin.getPassword())) {
            throw new BusinessException("密码错误");
        }

        //4. 登录成功
        //4-1 删除redis中的验证码
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE + uuid);

        //4-2 创建token
        Map map = new HashMap<>();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        String token = JwtUtil.createToken(map);

        //4-3 将token存入redis中
        admin.setPassword(null);//保存时,清除密码
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, JSON.toJSONString(admin), Duration.ofMinutes(60));

        //4-3 将token返回
        return token;
    }

    //管理员退出登录
    public void logout(String token) {
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN + token);
    }
}
